package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.request.HttpRequestUtil;
import com.teach.javafxclient.util.HttpUtil;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liang Jianlin
 * @date 2024-05-02 00:20
 */
public class CourseInfoController {
    @FXML
    public ImageView more;
    private Node Oroot;
    private Map<String,Node> paneMap = new HashMap<String,Node>();
    private Button temp;
    @FXML
    public Label name;
    @FXML
    public VBox stateBox;
    @FXML
    public Label state;
    @FXML
    public VBox typeBox;
    @FXML
    public VBox content;
    @FXML
    public Label type;
    @FXML
    public Label id;
    @FXML
    public ImageView avatar;
    @FXML
    public Label teacherName;
    @FXML
    public Button courseInfo;
    @FXML
    public Button announcement;
    @FXML
    public Button dataSource;
    @FXML
    public Button courseManage;
    Map<String,String> courseInfoMap = new HashMap<>();
    Map<String,String> assessmentMap = new HashMap<>();
    Map <String,String> timeType = new HashMap<>();
    JSONObject res;
    JSONObject time = new JSONObject();
    public void initialize (){
        timeType.put("all","所有周");
        timeType.put("even","双周");
        timeType.put("odd","单周");
        assessmentMap.put("GRADE","考核");
        assessmentMap.put("SCORE","考试");
        courseInfo.setOnAction(e-> {
            try {
                changeContentByScene("base/course-info-detail", getDetailNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        announcement.setOnAction(e-> {
            try {
                changeContentByScene("base/course-announcement", getAnnounceNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        dataSource.setOnAction(e-> {
            try {
                changeContentByScene("base/data-source", getDataSourceNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        courseManage.setOnAction(e-> {
            try {
                changeContentByScene("base/course-manage", getManageNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }
    private String getTimeString(JSONObject time) {
        String str = new String();
        str += "从第"+time.get("from")+"周到第"+time.get("to")+"周，"+timeType.get(time.get("type"));
        JSONArray timeArray = (JSONArray) time.get("time");
        for (int i = 0;i < timeArray.length();i++){
            str +="，周"+((JSONArray)timeArray.get(i)).get(0)+"第"+((JSONArray)timeArray.get(i)).get(1)+"节课";
        }
        str+="上课";
        return str;
    }

    private Node getDetailNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/course-info-detail.fxml"));
        System.out.println("ok");
        Parent root = fxmlLoader.load();
        CourseInfoDetailController CIDC = fxmlLoader.getController();
        CIDC.assessment.setText(assessmentMap.get(courseInfoMap.get("assessment")));
        CIDC.credit.setText(courseInfoMap.get("credit"));
        CIDC.college.setText(courseInfoMap.get("collegeName"));
        CIDC.term.setText(courseInfoMap.get("termName"));
        CIDC.courseLocation.setText(courseInfoMap.get("location"));
        CIDC.time.setText(getTimeString(time));
        CIDC.time.setWrapText(true);
        CIDC.introduction.setText(courseInfoMap.get("description"));
        CIDC.edit.setOnMouseClicked(e->{
            try {
                paneMap.put("base/course-info-detail",getEditNode());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            content.getChildren().clear();
            content.getChildren().add(paneMap.get("base/course-info-detail"));
        });
        CIDC.setTime(time.getJSONArray("time"));
        Oroot = root;
        return root;
    }
    private Node getEditNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/edit-course-info.fxml"));
        Parent root = fxmlLoader.load();
        EditCourseInfoController ECIC = fxmlLoader.getController();
        ECIC.giveup.setOnAction(e->{
            paneMap.remove("base/course-info-detail");
            try {
                changeContentByScene("base/course-info-detail", getDetailNode(),(Button) e.getSource());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        ECIC.set(courseInfoMap.get("collegeName"),courseInfoMap.get("credit"),courseInfoMap.get("location"),courseInfoMap.get("termName"),assessmentMap.get(courseInfoMap.get("assessment")),String.valueOf(time.get("from")),String.valueOf(time.get("to")),courseInfoMap.get("description"),courseInfoMap.get("courseId"),timeType.get(time.get("type")),res);
        return root;
    }
    private Node getAnnounceNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/course-announcement.fxml"));
        Parent root = fxmlLoader.load();
        CourseAnnouncementController CAC = fxmlLoader.getController();
        CAC.setAnnouncement(courseInfoMap.get("courseId"));
        HBox add = CAC.addAnnouncement;
        CAC.addAnnouncement.setOnMouseClicked(e-> {
            CAC.addContainer.getChildren().clear();
            FXMLLoader fxmlLoader2 = new FXMLLoader(MainApplication.class.getResource("base/add-announcement.fxml"));
            Parent root2;
            try {
                root2 = fxmlLoader2.load();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            AddAnnouncementController AAC = fxmlLoader2.getController();
            AAC.submit.setOnAction(e2 -> {
                JSONObject data = new JSONObject();
                data.put("title", AAC.title.getText());
                data.put("content", AAC.content.getText());
                data.put("relatedId", id.getText());
                data.put("type","COURSE");
                data.put("pinned",AAC.isPinned.isSelected());
                HttpResponse<JsonNode> response = HttpUtil.post(Globalvar.baseUrl + "/api/notices/course")
                        .header("Content-Type", "application/json")
                        .body(data)
                        .asJson();
                System.out.println(data);
                int statusCode = response.getStatus();
                if(statusCode == 200){
                    FXMLLoader fxmlLoader3 = new FXMLLoader(MainApplication.class.getResource("base/announcement-item.fxml"));
                    Parent root3;
                    try {
                        root3 = fxmlLoader3.load();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                    AnnouncementItemController AIC = fxmlLoader3.getController();
                    AIC.setItem(AAC.title.getText(),AAC.content.getText(),"发送成功",AAC.isPinned.isSelected(),null);
                    if(AAC.isPinned.isSelected()){
                        CAC.pinContainer.getChildren().add(root3);
                    }else{
                        CAC.itemContainer.getChildren().add(root3);
                    }
                }
                CAC.addContainer.getChildren().clear();
                CAC.addContainer.getChildren().add(add);
                System.out.println(statusCode);
            });
            CAC.addContainer.getChildren().add(root2);
        });
        return root;
    }
    private Node getDataSourceNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/data-source.fxml"));
        Parent root = fxmlLoader.load();
        DataSourceController CSC = fxmlLoader.getController();
        CSC.setSource(courseInfoMap.get("courseId"));
        return root;
    }
    private Node getManageNode() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/course-manage.fxml"));
        Parent root = fxmlLoader.load();
        CourseManageController CMC = fxmlLoader.getController();
        CMC.set(courseInfoMap.get("courseId"));
        return root;
    }

    public void setCourseInfo(String courseId){
        res = HttpUtil.get(Globalvar.baseUrl+"/api/courses/"+courseId)
                .header("Accept", "application/json")
                .asJson()
                .getBody()
                .getObject();
        System.out.println(res);
        courseInfoMap.put("courseId", (String) res.get("courseId"));
        courseInfoMap.put("termName", (String) res.get("termName"));
        courseInfoMap.put("collegeName", (String) res.get("collegeName"));
        courseInfoMap.put("teacherName", (String) res.get("teacherName"));
        courseInfoMap.put("name", (String) res.get("name"));
        courseInfoMap.put("termId", String.valueOf(res.get("termId")));
        courseInfoMap.put("collegeId", String.valueOf(res.get("collegeId")));
        courseInfoMap.put("teacherId", String.valueOf(res.get("teacherId")));
        courseInfoMap.put("type", (String) res.get("type"));
        courseInfoMap.put("state", (Boolean) res.get("ended")?"已结课":"进行中");
        courseInfoMap.put("credit", String.valueOf(res.get("credit")));
        courseInfoMap.put("description", (String) res.get("description"));
        courseInfoMap.put("location", (String) res.get("location"));
        courseInfoMap.put("capacity", String.valueOf(res.get("capacity")));
        courseInfoMap.put("assessment", (String) res.get("assessment"));
        time = (JSONObject) res.get("time");
        name.setText(courseInfoMap.get("name"));
        teacherName.setText(courseInfoMap.get("teacherName"));
        id.setText(courseId);
        type.setText(courseInfoMap.get("type"));
        typeBox.setStyle("-fx-background-color:"+Globalvar.courseTypeColorMap.get(courseInfoMap.get("type"))+";-fx-background-radius:8;-fx-border-radius:8;-fx-border-color:#707070");
        state.setText(courseInfoMap.get("state"));
        stateBox.setStyle((Boolean) res.get("ended")?"-fx-background-color: #c0392b;-fx-background-radius:8;-fx-border-radius:8;-fx-border-color:gray;":"-fx-background-color: #CDF3C6;-fx-background-radius:8;-fx-border-radius:8;-fx-border-color:gray;");
        state.setTextFill(Paint.valueOf((Boolean) res.get("ended")?"white":"#5c5b5b"));
        teacherName.setText(courseInfoMap.get("teacherName"));
        String teacherId = courseInfoMap.get("teacherId");
        HttpResponse response = HttpUtil.get(Globalvar.baseUrl+"/api/users/"+teacherId+"/avatar")
                .header("Accept", "application/json") // 设置请求头（如果需要的话）
                .asBytes();
        System.out.println("收到响应");
        Image img;
        if(response.getStatus() == 404){
            img = new Image(getClass().getResource("/com/teach/javafxclient/picture/用户-圆.png").toExternalForm());
        }else{
            img = new Image(new ByteArrayInputStream((byte[]) response.getBody()));
        }
        double wid = Math.min(img.getWidth() , img.getHeight());
        Circle clip = new Circle(avatar.getFitWidth() / 2, avatar.getFitHeight() / 2, Math.min(avatar.getFitWidth() , avatar.getFitHeight()) / 2);
        avatar.setClip(clip);
        Rectangle2D viewport = new Rectangle2D(img.getWidth()/2 - wid/2, img.getHeight()/2 - wid/2, wid, wid);
        avatar.setViewport(viewport);
        avatar.setImage(img);
    }
    protected  void changeContentByScene(String name, Node n, Button button) {
        if(temp != null){
            temp.setStyle("-fx-text-fill: #707070;-fx-background-color: white");
            temp.setUnderline(false);
        }
        button.setStyle("-fx-text-fill: #670202;-fx-background-color: white");
        button.setUnderline(true);
        temp = button;
        Node node;
        Object c;
        node = paneMap.get(name);
        if( node == null) {
            node = n;
        }
        content.getChildren().clear();
        content.getChildren().add(node);
    }
}